package cn.hdmis.util;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.util.StringUtil;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.hdmis.security.entity.User;
import cn.hdmis.shiro.SecurityUtils;


public class AccountManager {
	
	private static final long serialVersionUID = 5040590745066541071L;
	public final Logger logger  = LoggerFactory.getLogger(getClass());
	private static AccountManager accountManager = new AccountManager();
	private AccountManager(){};
	
	public static AccountManager getInstance(){
		return accountManager;
	}
	public SysMessageBean login(User user){
		
		Subject currentUser = SecurityUtils.getSubject();
		if (!currentUser.isAuthenticated()) {
			if(null==user||StringUtils.isBlank(user.getName())||StringUtils.isBlank(user.getPassword())){
				return  new SysMessageBean("error", "登录账号或密码不能为空!");
			}
			UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), user.getPassword());
			token.setRememberMe(false);
			try {
				currentUser.login(token);
				logger.debug("There is user with username of "+ token.getPrincipal()+"is login successful!");
			}catch(UnknownAccountException e){
				logger.error(token.getPrincipal()+"登录验证未通过!", e.getMessage());
				return  new SysMessageBean("error", "账号信息错误,请核对后重新输入!");
			}catch (AuthenticationException e) {
				logger.error(token.getPrincipal()+"登录验证未通过!", e.getMessage());
				return  new SysMessageBean("error", "账号认证异常!");
			}catch (Exception e) {
				logger.error(token.getPrincipal()+"登录验证未通过!", e.getMessage());
				return  new SysMessageBean("error", "验证异常,未通过验证!");
				
			}
		}
		return new SysMessageBean("success", "登录验证通过!");
	}
		
	public void loginOut(){
		Subject currentUser = SecurityUtils.getSubject();
		currentUser.logout();
	}

}
